<template>
  <div class="orgInfo-container">
    <div class="header-title">机构人员管理</div>
    <el-divider></el-divider>
    <el-form ref="formRef" :rules="rules" :model="form" label-width="100px">
      <el-form-item label="启用状态" prop="status">
        <el-radio-group v-model="form.status">
          <el-radio label="1">启用</el-radio>
          <el-radio label="0">禁用</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="账号" prop="account">
        <el-input
          v-model="form.account"
          placeholder="请输入账号"
          :disabled="id !== undefined && id !== null"
          @change="validAccF"
        ></el-input>
      </el-form-item>
      <el-form-item label="修改密码" prop="password">
        <el-input
          v-if="!id || !form.userId"
          type="password"
          v-model="form.password"
          placeholder="请输入8～16位,含字母、数字、符号的密码"
        ></el-input>
        <el-button v-else type="text" @click="passwordChange">修改</el-button>
      </el-form-item>
      <el-form-item
        v-if="!id || !form.userId"
        label="确认密码"
        prop="confirmPW"
      >
        <el-input
          type="password"
          v-model="form.confirmPW"
          placeholder="请输入确认密码"
        ></el-input>
      </el-form-item>
      <el-form-item label="角色" prop="roleId">
        <el-select remote v-model="form.roleId" placeholder="请选择角色">
          <el-option
            v-for="item in roleOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="姓名" prop="doctorName">
        <el-input v-model="form.doctorName" placeholder="请输入姓名"></el-input>
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="form.phone" placeholder="请输入手机号"></el-input>
      </el-form-item>
      <el-form-item label="科室" prop="departmentId">
        <el-select v-model="form.departmentId" placeholder="请选择科室">
          <el-option
            v-for="item in departmentOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="性别" prop="sex">
        <el-select v-model="form.sex" placeholder="性别">
          <el-option
            v-for="item in [
              { value: 1, label: '男' },
              { value: 0, label: '女' },
            ]"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="职位" prop="title">
        <el-input v-model="form.title" placeholder="请输入职位"></el-input>
      </el-form-item>
      <el-form-item label="擅长领域" prop="skillPoints">
        <el-input
          v-model="form.skillPoints"
          placeholder="请输入擅长领域"
        ></el-input>
      </el-form-item>
      <el-form-item label="医生简介" prop="doctorDesc">
        <el-input
          type="textarea"
          v-model="form.doctorDesc"
          placeholder="请输入医生简介"
        ></el-input>
      </el-form-item>
      <el-form-item label="职业经历" prop="position">
        <el-input
          type="textarea"
          v-model="form.position"
          placeholder="请输入职业经历"
        ></el-input>
      </el-form-item>
      <el-form-item v-if="id" label="医生二维码" prop="qrUrl">
        <div class="avatar-uploader" disabled>
          <img :src="form.qrUrl" class="avatar" />
        </div>
      </el-form-item>
      <el-form-item label="头像" prop="avatar">
        <img-upLoad
          v-model="form.avatar"
          :isDataWithJSON="false"
          :maxCount="1"
          ref="avatarImgUploadRef"
        ></img-upLoad>
        <!-- <el-upload
          class="avatar-uploader"
          :headers="{ ContentType: 'multipart/form-data', auth: token }"
          :action="uploadUrl"
          :show-file-list="false"
          :on-success="
            (val) => {
              form.avatar = val.data
            }
          "
        >
          <img v-if="form.avatar" :src="form.avatar" class="avatar" />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload> -->
      </el-form-item>
      <el-form-item label="医生签名" prop="signatureImg">
        <img-upLoad
          v-model="form.signatureImg"
          :isDataWithJSON="false"
          :maxCount="1"
          ref="imgUploadRef"
        ></img-upLoad>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">提交</el-button>
        <el-button @click="goBack">返回上一页</el-button>
      </el-form-item>
    </el-form>
    <edit-password v-model="dialog" :userId="form.userId" />
    <edit-password v-model="isBindAcc" :account="form.account" />
  </div>
</template>
<script>
  import { reactive, ref, computed, onBeforeMount } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { roles } from '@/api/modules/role'
  import { validAcc } from '@/api/user'
  import { departments } from '@/api/modules/departments'
  import { useRouter, useRoute } from 'vue-router'
  import { save, getOrgPersonInfo } from '@/api/modules/orgPerson.js'
  import { clone } from 'lodash'
  import md5 from 'md5'
  import imgUpLoad from '@/components/ImgFileUpload'
  // import { objToRangeJson, rangeJsonToObj } from '@/utils/converter.js'
  import EditPassword from '@/components/EditPassword'
  import common from '@/utils/common'
  export default {
    name: 'personnelInfo',
    components: { EditPassword, imgUpLoad },
    setup() {
      // 公用方法
      const router = useRouter()
      const route = useRoute()

      // 生命周期及初始化
      const roleOptions = ref([])
      const departmentOptions = ref([])
      const search = { pageIndex: 1, pageSize: 500 }
      let id = ref(null)
      id.value = route.query.id

      const initData = function (data) {
        Object.keys(data).forEach((item) => {
          if (item === 'avatar' || item === 'signatureImg') {
            if (data[item]) {
              form[item] = JSON.stringify([{ url: data[item] }])
            }
          } else {
            form[item] = data[item]
          }
        })
        form.status = form.status + ''
      }
      onBeforeMount(() => {
        const arr = [roles(search), departments(search)]
        if (id.value) {
          id.value = route.query.id
          arr.push(getOrgPersonInfo({ id: id.value }))
          // TODO 加载用户数据
        }
        Promise.all(arr)
          .then((values) => {
            roleOptions.value = values[0].data.map((item) => {
              return { value: item.id, label: item.roleName }
            })
            departmentOptions.value = values[1].data.map((item) => {
              return { value: item.id, label: item.name }
            })
            if (values[2]) initData(values[2].data)
          })
          .catch((err) => {
            console.log('err =' + JSON.stringify(err))
          })
      })

      // 事件处理
      const goBack = function () {
        router.go(-1)
      }

      // 表单相关
      const form = reactive({
        status: null, // 禁用状态
        account: null,
        password: '',
        confirmPW: '',
        roleId: null, // 角色ID
        doctorName: null,
        phone: null,
        departmentId: null, // 科室ID
        position: null, // 职位
        skillPoints: null, //擅长领域
        doctorDesc: null,
        experience: null,
        admissionTime: null, // 存储表格转换后的JSON字符串
        avatar: null, // 头像地址
        qrUrl: null, // 二维码地址
        signatureImg: null, //签名地址
        userId: null,
      })

      let isBindAcc = ref(false)
      const validAccF = async function (cb) {
        const res = await validAcc({ account: form.account })
        if (typeof cb === 'function') {
          cb()
          return
        }
        if (res.data) {
          ElMessageBox.confirm(
            '该账号已被注册，请确定是否进入绑定流程',
            '提示',
            {
              confirmButtonText: '开始绑定',
              cancelButtonText: '更换账号',
              type: 'warning',
              center: true,
            }
          )
            .then(() => {
              isBindAcc.value = true
            })
            .catch(() => {})
        }
      }

      const validateImage = (rule, value, callback) => {
        if (value === '' || value === '[]') {
          callback(new Error('请上传图片'))
        }
        callback()
      }
      const rules = {
        status: [
          { required: true, message: '请选择启禁用状态', trigger: 'blur' },
        ],
        account: [
          {
            required: true,
            min: 6,
            max: 18,
            message: '请输入6～18位账号',
            trigger: 'blur',
          },
        ],
        doctorName: [
          { required: true, min: 1, message: '请输入姓名', trigger: 'blur' },
        ],
        phone: [
          { required: true, min: 6, message: '请输入手机号', trigger: 'blur' },
        ],
        roleId: [{ required: true, message: '请选择角色', trigger: 'blur' }],
        departmentId: [
          { required: true, message: '请选择科室状态', trigger: 'blur' },
        ],
        avatar: [
          { required: true, message: '请上传医生头像', trigger: 'blur' },
          { required: true, trigger: 'blur', validator: validateImage },
        ],
        signatureImg: [
          { required: true, message: '请上传医生签名', trigger: 'blur' },
          { required: true, trigger: 'blur', validator: validateImage },
        ],
      }
      if (!id.value) {
        const validF = function (rules, value, cb) {
          if (form.password !== form.confirmPW) {
            cb(new Error('两次密码要输入一样'))
          }
          cb()
        }
        const checkPasswordF = function (rules, value, cb) {
          if (!common.checkPassword(form.password)) {
            cb(new Error('请输入8～16位,含字母、数字、符号的密码'))
          }
          cb()
        }
        rules['password'] = [
          {
            required: true,
            min: 8,
            max: 16,
            message: '请输入8～16位,含字母、数字、符号的密码',
            trigger: 'blur',
          },
          {
            required: true,
            validator: checkPasswordF,
            message: '请输入8～16位,含字母、数字、符号的密码',
            trigger: 'blur',
          },
        ]
        rules['confirmPW'] = [
          {
            required: true,
            validator: validF,
            message: '两次密码要输入一样',
            trigger: 'blur',
          },
        ]
      }

      const formRef = ref(null)
      const imgUploadRef = ref()
      const avatarImgUploadRef = ref()
      const onSubmit = function () {
        const status = imgUploadRef.value.getStatus()
        const statusWithAvatar = avatarImgUploadRef.value.getStatus()
        if (!status || !statusWithAvatar) {
          ElMessage.warning('图片还在上传')
          return
        }
        formRef.value.validate((valid) => {
          console.log('from =' + JSON.stringify(form))
          if (valid) {
            // TODO 调用接口，返回上一页
            // form.admissionTime = objToRangeJson(tableData.value)
            validAccF(() => {
              let formC = clone(form)
              if (formC.userId) {
                delete formC.password
                delete formC.confirmPW
              } else {
                formC.password = md5(formC.password)
              }
              if (formC['avatar']) {
                formC['avatar'] = JSON.parse(formC['avatar'])[0].url
              }
              if (formC['signatureImg']) {
                formC['signatureImg'] = JSON.parse(formC['signatureImg'])[0].url
              }
              save(formC)
              ElMessage.success('提交成功')
              goBack()
            })
          }
        })
      }
      // 排班表相关代码
      let tableData = ref([
        {
          title: '周一',
          range0: null,
          range1: null,
          range2: null,
          range3: null,
          range4: null,
          range5: null,
          range6: null,
          range7: null,
        },
        {
          title: '周二',
          range0: null,
          range1: null,
          range2: null,
          range3: null,
          range4: null,
          range5: null,
          range6: null,
          range7: null,
        },
        {
          title: '周三',
          range0: null,
          range1: null,
          range2: null,
          range3: null,
          range4: null,
          range5: null,
          range6: null,
          range7: null,
        },
        {
          title: '周四',
          range0: null,
          range1: null,
          range2: null,
          range3: null,
          range4: null,
          range5: null,
          range6: null,
          range7: null,
        },
        {
          title: '周五',
          range0: null,
          range1: null,
          range2: null,
          range3: null,
          range4: null,
          range5: null,
          range6: null,
          range7: null,
        },
        {
          title: '周六',
          range0: null,
          range1: null,
          range2: null,
          range3: null,
          range4: null,
          range5: null,
          range6: null,
          range7: null,
        },
        {
          title: '周日',
          range0: null,
          range1: null,
          range2: null,
          range3: null,
          range4: null,
          range5: null,
          range6: null,
          range7: null,
        },
      ])
      let timeRange = ref([[0]])

      const getLabel = function (index) {
        return '时间' + (index + 1)
      }

      const getProp = function (index) {
        return 'timeRange' + (index + 1)
      }

      const rangeChange = function (event, row, index, item) {
        console.log(
          'event =' +
            JSON.stringify(event) +
            'row =' +
            JSON.stringify(row) +
            'y =' +
            JSON.stringify(index) +
            'x =' +
            JSON.stringify(item)
        )
      }

      const addx = function () {
        if (timeRange.value.length >= 8) {
          ElMessage.warning('暂时只支持8个时间段')
          return
        }
        timeRange.value.push([timeRange.value.length])
      }

      const addy = function () {
        const tmp = {
          title: '周一',
          range0: null,
          range1: null,
          range2: null,
          range3: null,
          range4: null,
          range5: null,
          range6: null,
          range7: null,
        }
        tableData.value.push(tmp)
      }

      // 文件上传
      const uploadUrl = computed(() => {
        return process.env.VUE_APP_BASE_URL + '/emrweb/file/upload'
      })

      const handleAvatarSuccess = function (val) {
        console.log('上传成功' + JSON.stringify(val))
        form.img = val.data
      }

      // 密码弹窗相关
      let dialog = ref(false)
      const passwordChange = function () {
        dialog.value = true
      }
      return {
        form,
        getLabel,
        getProp,
        tableData,
        timeRange,
        rangeChange,
        addy,
        addx,
        uploadUrl,
        handleAvatarSuccess,
        roleOptions,
        departmentOptions,
        goBack,
        onSubmit,
        dialog,
        passwordChange,
        formRef,
        id,
        rules,
        validAccF,
        isBindAcc,
        imgUploadRef,
        avatarImgUploadRef,
      }
    },
  }
</script>
<style lang="scss" scoped>
  .orgInfo-container {
    margin: 32px;
    background-color: white;
    overflow: hidden;
    width: 100%;

    .header-title {
      margin-top: 20px;
      margin-left: 11px;
    }

    .el-form {
      width: 50%;

      .el-select {
        width: 100%;
      }

      .el-input {
        width: 100% !important;
      }
    }

    .el-form {
      .el-form-item {
        :deep(.el-form-item__content) {
          width: 100%;
        }
      }
    }

    .work-container {
      display: flex;
      flex-wrap: wrap;
    }

    .avatar-uploader :deep(.el-upload) {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
    }

    .avatar-uploader :deep(.el-upload:hover) {
      border-color: #409eff;
    }

    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 148px;
      height: 148px;
      line-height: 148px;
      text-align: center;
    }

    .avatar {
      width: 148px;
      height: 148px;
      display: block;
    }
  }
</style>
